package com.egao.orderB.biz.impl;

import com.egao.common.core.damon.constant.UserConstant;
import com.egao.common.core.damon.results.BaseDao;
import com.egao.common.core.damon.results.PageResult2;
import com.egao.common.core.damon.utils.PinyinUtils;
import com.egao.common.core.damon.utils.Utils;
import com.egao.common.core.web.JsonResult;
import com.egao.common.system.entity.User;
import com.egao.orderB.biz.ElectricFenceBiz;
import com.egao.orderB.entity.ElectricFence;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 数据层实现类
 * @author : Doman
 * @date : 2020-12-22 15:23:23
 * @version ：1.0
 */
@Repository
public class ElectricFenceBizImpl extends BaseDao implements ElectricFenceBiz {

	@Override
	public JsonResult list(PageResult2<T> page, ElectricFence electricFence, User loginUser) throws Exception {
		Map<String, String> map  = new HashMap<String, String>();
		RowMapper<ElectricFence> rm = new BeanPropertyRowMapper<ElectricFence>(ElectricFence.class);
		StringBuffer sql = new StringBuffer("select e.id,e.organization_id,e.name");
        sql.append(",e.longitude,e.latitude,e.radius,e.state,e.type");
		sql.append(",e.remark,e.create_time,e.create_user,e.update_time");
		sql.append(",e.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.username createName ");
        sql.append(" from chf_electric_fence e ");
        sql.append(" inner join sys_user suser on suser.user_id=e.create_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=e.organization_id ");
        sql.append(" where e.deleted=0 and sogzn.deleted=0 ");
		if(loginUser.getUserId() != UserConstant.ADMIN_ID){
            sql.append(" and e.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
    	if(Utils.isNotEmpty(electricFence)){
			if(Utils.isNotEmpty(electricFence.getName())){
				sql.append(" and (instr(e.name,:name)>0 or instr(e.pinyin,:name)>0) ");
				map.put("name", electricFence.getName());
			}
			if(Utils.isNotEmpty(electricFence.getType())){
				sql.append(" and instr(e.type,:type)>0 ");
				map.put("type", electricFence.getType());
			}
			if(Utils.isNotEmpty(electricFence.getSort())&&Utils.isNotEmpty(electricFence.getOrder())){
                sql.append(" order by e."+electricFence.getSort()+" "+electricFence.getOrder());
            } else {
                sql.append(" order by e.create_time desc");
            }
		}
		return jsonResult(getPageQueryList(page, sql.toString(), map, rm));
	}

	@Override
	public List<ElectricFence> list(ElectricFence electricFence, User loginUser) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> map2  = new HashMap<String, String>();
		RowMapper<ElectricFence> rm = new BeanPropertyRowMapper<ElectricFence>(ElectricFence.class);
        StringBuffer sql = new StringBuffer("select e.id,e.organization_id,e.name");
        sql.append(",e.longitude,e.latitude,e.radius,e.state,e.type");
		sql.append(",e.remark,e.create_time,e.create_user,e.update_time");
		sql.append(",e.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.username createName ");
        sql.append(" from chf_electric_fence e ");
        sql.append(" inner join sys_user suser on suser.user_id=e.create_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=e.organization_id ");
        sql.append(" where e.deleted=0 and sogzn.deleted=0 ");
		if(loginUser.getUserId() != UserConstant.ADMIN_ID){
            sql.append(" and e.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId());
			map2.put("tableOrganizationId", loginUser.getOrganizationId()+"");
        }
    	if(Utils.isNotEmpty(electricFence)){
			if(Utils.isNotEmpty(electricFence.getName())){
				sql.append(" and (instr(e.name,:name)>0 or instr(e.pinyin,:name)>0) ");
				map.put("name", electricFence.getName());
				map2.put("name", electricFence.getName());
			}
			if(Utils.isNotEmpty(electricFence.getType())){
				sql.append(" and instr(e.type,:type)>0 ");
				map.put("type", electricFence.getType());
				map2.put("type", electricFence.getType());
			}
//			if(Utils.isNotEmpty(electricFence.getEfIds())){
//				sql.append(" and e.id in (:id) ");
//				map.put("id", electricFence.getEfIds());
//				map2.put("id", electricFence.getEfIds().toString());
//			}
            if(Utils.isNotEmpty(electricFence.getSort())&&Utils.isNotEmpty(electricFence.getOrder())){
				sql.append(" order by e."+electricFence.getSort()+" "+electricFence.getOrder());
			} else {
				sql.append(" order by e.create_time desc");
			}
		}
		getMapParameter(sql, map2);
		return jdbcTemplate.query(sql.toString(),map, rm);
	}

	@Override
	public List<ElectricFence> factoryYardDockEfs(ElectricFence electricFence) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> map2  = new HashMap<String, String>();
		RowMapper<ElectricFence> rm = new BeanPropertyRowMapper<ElectricFence>(ElectricFence.class);
        StringBuffer sql = new StringBuffer("");
		sql.append(" select fa.name,fa.longitude,fa.latitude,fa.radius,fa.yard_dock type from chf_maintain_fee_attach fa ");
		sql.append(" where fa.type='平台' and fa.deleted=0 and fa.longitude is not null ");
		sql.append(" and fa.latitude is not null and fa.radius !=0 and fa.yard_dock is not null ");
		sql.append(" and fa.id in (:yardDockIds) ");
		map.put("yardDockIds", electricFence.getYardDockIds());
		map2.put("yardDockIds", electricFence.getYardDockIds().toString());

		sql.append(" union all ");
		sql.append(" select af.faddress name,af.longitude,af.latitude,radius,'工厂' type from chf_address_factory af ");
		sql.append(" where af.customer_id != 0 and af.deleted = 0 and af.longitude is not null ");
		sql.append(" and af.latitude is not null and af.radius !=0 ");
		sql.append(" and af.bill_id=:bill_id ");
		map.put("bill_id", electricFence.getBillId());
		map2.put("bill_id", electricFence.getBillId());
		getMapParameter(sql, map2);
		return jdbcTemplate.query(sql.toString(),map, rm);
	}

	@Override
	public ElectricFence getById(ElectricFence electricFence) {
		RowMapper<ElectricFence> rm = new BeanPropertyRowMapper<ElectricFence>(ElectricFence.class);
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql = new StringBuffer("select e.id,e.organization_id,e.name");
        sql.append(",e.longitude,e.latitude,e.radius,e.state,e.type");
		sql.append(",e.remark,e.create_time,e.create_user,e.update_time");
		sql.append(",e.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.username createName ");
        sql.append(" from chf_electric_fence e ");
        sql.append(" inner join sys_user suser on suser.user_id=e.create_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=e.organization_id ");
        sql.append(" where e.deleted=0 and sogzn.deleted=0 and e.id=:id ");
		map.put("id", electricFence.getId());
		getMapParameter(sql, map);
		return jdbcTemplate.queryForObject(sql.toString(), map, rm);
	}

	@Override
	public Integer save(ElectricFence electricFence, User loginUser) {
		GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
		KeyHolder keyHolder=new GeneratedKeyHolder();
		electricFence.setPinyin(PinyinUtils.ToFirstChar(electricFence.getName()));
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql =new StringBuffer("insert into chf_electric_fence (");
        sql.append("organization_id,name,longitude,latitude,type,pinyin");
		sql.append(",radius,state,remark,create_user,create_time) values ( ");
        sql.append(":organization_id,:name,:longitude,:latitude,:type,:pinyin");
		sql.append(",:radius,:state,:remark,:create_user,now())");
        map.put("organization_id", loginUser.getOrganizationId() + "");
        map.put("name", electricFence.getName());
        map.put("longitude", electricFence.getLongitude());
        map.put("latitude", electricFence.getLatitude());
        map.put("type", electricFence.getType());
        map.put("pinyin", electricFence.getPinyin());
        map.put("radius", electricFence.getRadius());
        map.put("state", electricFence.getState());
        map.put("remark", electricFence.getRemark());
		map.put("create_user", loginUser.getUserId() + "");
		getMapParameter(sql, map);
		int retVal = this.jdbcTemplate.update(sql.toString(), new SqlParameterSource() {
			@Override
			public boolean hasValue(String paramName) {
				return map.containsKey(paramName);
			}
			@Override
			public Object getValue(String paramName) throws IllegalArgumentException {
				return map.get(paramName);
			}
		}, generatedKeyHolder);

		Integer id = generatedKeyHolder.getKey().intValue();
		return id;
	}

	@Override
	public boolean update(ElectricFence electricFence, User loginUser) {
		electricFence.setPinyin(PinyinUtils.ToFirstChar(electricFence.getName()));
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql =new StringBuffer("update chf_electric_fence set ");
        sql.append("name=:name,longitude=:longitude,latitude=:latitude,type=:type ");
		sql.append(",pinyin=:pinyin ");
		sql.append(",radius=:radius,state=:state,remark=:remark ");
		sql.append(",update_time=now(),update_user=:update_user where id=:id ");
        map.put("name", electricFence.getName());
        map.put("longitude", electricFence.getLongitude());
        map.put("latitude", electricFence.getLatitude());
        map.put("type", electricFence.getType());
		map.put("pinyin", electricFence.getPinyin());
        map.put("radius", electricFence.getRadius());
        map.put("state", electricFence.getState());
        map.put("remark", electricFence.getRemark());
		map.put("update_user", loginUser.getUserId() + "");
		map.put("id", electricFence.getId());
		getMapParameter(sql, map);
		int count = jdbcTemplate.update(sql.toString(), map);
		return count > 0;
	}

	@Override
	public boolean remove(ElectricFence electricFence, User loginUser) {
		int count = 0;
		Map<String, String> map = null;
		if(electricFence.getId().length()>0){
			for(String ID : electricFence.getId().split(",")){
				map  = new HashMap<String, String>();
				if(ID==null || ID.equals("")){ break; }
				StringBuffer sql =new StringBuffer("update chf_electric_fence set deleted=1" +
						",update_user=:update_user, update_time=now() "
						+ " where id =:id ");
				map.put("update_user", loginUser.getUserId() + "");
				map.put("id", ID);
				getMapParameter(sql, map);
				count = jdbcTemplate.update(sql.toString(),map);
			}
		}
		return count > 0;
	}
}
